﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Appkiz.Library.Security;
using Appkiz.Library.Security.Authentication;
using Appkiz.Apps.Calendar.Models.Business;
using Appkiz.Apps.Calendar.Models.Data;
using Appkiz.Apps.Calendar.Models.ViewModel;
using Tiger.Common;
using FluentDateTime;
using Appkiz.Library.Common;
using Appkiz.Apps.Calendar.Models.Business.TaskUpdaters;
using System.Linq.Expressions;
using System.IO;
using Newtonsoft.Json;
using Tiger.Models;

namespace Tiger.Controllers
{
    public class GroupCalendarController : Controller
    {
        private OrgMgr orgMgr = new OrgMgr();
        private CalendarEntities calendarEntities = new CalendarEntities();

        #region 获得日程列表
        /// <summary>
        /// 获得日程列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTasksByWeek()
        {
            /*
             * 变量定义
             */
            // 查询开始日期
            DateTime StartDate;
            // 查询结束日期
            DateTime EndDate;
            // 上一个周一日期
            DateTime PrevMonday;
            // 下一个周一日期
            DateTime NextMonday;
            // 日期范围中所有日期列表
            List<DateTime> DateArray = new List<DateTime>();

            /*
             * 参数获取
             */
            // 用户ID
            var uid = Request.Params["uid"];
            // 今天日期
            var date = Request.Params["date"];
            // 当前周一
            var currentMonday = Request.Params["dateOfCurrentMonday"];

            /*
             * 参数校验
             */
            // 用户ID
            var employee = orgMgr.GetEmployee(uid);
            if(employee == null)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "用户不存在"
                });
            }
            // 当前日期
            DateTime todayDate;
            if(!DateTime.TryParse(date, out todayDate))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "当前日期格式不正确"
                });
            }
            // 当前周一
            DateTime currentMondayDate;
            if (!DateTime.TryParse(currentMonday, out currentMondayDate))
            {
                // 判断是否是应该传入的日期
                if (!string.IsNullOrEmpty(currentMonday))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "当前周一格式不正确"
                    });
                }
            }
            
            /*
             * 查询任务
             */
            // 确定开始日期
            if(!string.IsNullOrEmpty(currentMonday))
            {
                StartDate = currentMondayDate;
            }
            else
            {
                StartDate =  DateUtil.StartOfWeek(DateTime.Now, DayOfWeek.Monday);
            }
            // 确定结束日期
            EndDate = DateTimeExtensions.Next(StartDate, DayOfWeek.Sunday);
            // 确定上周一
            PrevMonday = DateTimeExtensions.Previous(StartDate, DayOfWeek.Monday);
            // 确定下周一
            NextMonday = DateTimeExtensions.Next(StartDate, DayOfWeek.Monday);

            // 查询任务
            List<TaskViewModel> tasks = TaskBiz.GetTaskListBetweenDays(StartDate, EndDate, true, true, employee.EmplID, calendarEntities);
            SortedDictionary<string, List<object>> dict = new SortedDictionary<string, List<object>>();
            foreach(TaskViewModel task in tasks)
            {
                // Key
                var StartDateString = task.StartDateString;
                List<object> list;
                // 检测字典中是否存在日期key
                if (dict.ContainsKey(StartDateString))
                {
                    // 取出列表
                    list = dict[StartDateString];
                    list.Add(new
                    {
                        StartTime = task.StartTimeString,
                        Content = task.Title,
                        IsFinished = task.IsFinished
                    });
                }
                else
                {
                    // 新建列表
                    list = new List<object>();
                    list.Add(new
                    {
                        StartTime = task.StartTimeString,
                        Content = task.Title,
                        IsFinished = task.IsFinished
                    });
                    dict[StartDateString] = list;
                }
            }

            // 检查是否有需要插入的日期
            // 当前已有日期列表
            List<string> CurrentDateArray = dict.Keys.ToList();
            // 所有中间日期列表
            DateArray = Enumerable.Range(0, 1+EndDate.Subtract(StartDate).Days)
                .Select(offset => StartDate.AddDays(offset))
                .ToList();
            foreach(DateTime dateTime in DateArray)
            {
                if (!CurrentDateArray.Contains(dateTime.ToString("yyyy-MM-dd")))
                {
                    dict[dateTime.ToString("yyyy-MM-dd")] = new List<object>();
                }
            }

            // 返回结果
            var ResultList = new List<object>();
            foreach(KeyValuePair<string, List<object>> item in dict)
            {
                DateTime dateTime = DateTime.Parse(item.Key);

                ResultList.Add(new
                {
                    Date = dateTime.ToString("yyyy-MM-dd"),
                    Day = System.Globalization.DateTimeFormatInfo.CurrentInfo.DayNames[(byte)dateTime.DayOfWeek],
                    Tasks = item.Value
                });
            }

            return new JsonNetResult(new
            {
                DateTimeOfNextMonday = NextMonday.ToString("yyyy-MM-dd"),
                DateTimeOfPrevMonday = PrevMonday.ToString("yyyy-MM-dd"),
                Content = ResultList
            });
        }
        #endregion

        #region 获取工作组人员列表
        /// <summary>
        /// 获取工作组人员列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetGroupUsers()
        {
            /*
             * 参数获取
             */
            // 获得领导角色组名称
            string GroupRoleName = System.Configuration.ConfigurationManager.AppSettings["GroupRoleName"];

            // 获得该组内所有成员
            var sql = @"SELECT
                            ORG_Employee.* 
                        FROM 
                            ORG_Employee 
                        JOIN 
                            ORG_EmplRole 
                        ON 
                            ORG_Employee.EmplID = ORG_EmplRole.EmplID 
                        JOIN 
                            ORG_Role 
                        ON 
                            ORG_EmplRole.RoleID = ORG_Role.RoleID 
                        AND 
                            ORG_Role.RoleName = '{0}'
                        ORDER BY
                            ORG_Employee.GlobalSortNo
                        DESC";

            List<Employee> EmployeeList = orgMgr.FindEmployeeBySQL(string.Format(sql, GroupRoleName));
            var ResultList = new List<object>();
            foreach(Employee employee in EmployeeList)
            {
                var originName = employee.EmplName;
                var finalName = originName;
                ResultList.Add(new {
                    EmplID = employee.EmplID,
                    Name = finalName
                });
            }

            return new JsonNetResult(new
            {
                Succeed = true,
                Data = new {
                    Users = ResultList
                }
            });
        }
        #endregion

        #region 检测当前用户是否有查看领导日程权限
        /// <summary>
        /// 检测当前用户权限
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckLeaderPermission()
        {
            try
            {
                // 获得当前用户
                var employee = (User.Identity as AppkizIdentity).Employee;
                bool canSeeLeader = AppPermission.CheckPermission(employee.EmplID, "canSeeLeader");
                if (canSeeLeader == true)
                {
                    return new JsonNetResult(new
                    {
                        Succeed = true,
                        Data = new
                        {
                            flag = true
                        }
                    });
                }
                else
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Data = new
                        {
                            flag = false
                        }
                    });
                }
            }
            catch
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Data = new
                    {
                        flag = false
                    }
                });
            }
        }
        #endregion

        #region 新建领导日程
        /// <summary>
        /// 新建领导日程
        /// </summary>
        /// <param name="startDate">开始日期</param>
        /// <param name="title">内容</param>
        /// <param name="emplID">领导ID</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult NewTask(DateTime? startDate, string title, string emplID)
        {
            try
            {
                /*
                 * 参数校验
                 */
                // 领导ID
                var leaderEmployee = orgMgr.GetEmployee(emplID);
                if(leaderEmployee == null)
                {
                    return new JsonNetResult(new
                    {
                        Success = false,
                        Message = "领导ID无效"
                    });
                }
                else
                {
                    using (CalendarEntities dbInstance = DBHelper.GetDbInstance())
                    {
                        TaskBiz.NewTask(title, startDate, emplID, dbInstance, (string)null, (string)null, (string)null);
                        return this.Json((object)new
                        {
                            Success = true,
                            Message = "日程创建成功"
                        });
                    }
                }
            }
            catch(Exception e)
            {
                LogService.WriteLog("Tiger", "Message:" + e.Message, "Tiger_Debug", LogService.LogLevel.Debug);
                return new JsonNetResult(new
                {
                    Success = false,
                    Message = e.Message
                });
            }
        }
        #endregion

        #region 删除领导日程
        /// <summary>
        /// 删除领导日程
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteTask(Guid[] idList)
        {
            using (CalendarEntities dbInstance = DBHelper.GetDbInstance())
            {
                foreach (Guid id in idList)
                    TaskBiz.DeleteTask(id, dbInstance, this.HttpContext.ApplicationInstance.Context);
            }
            return this.Json((object)new { Success = true });
        }
        #endregion

        #region 更新领导日程
        /// <summary>
        /// 更新领导日程
        /// </summary>
        /// <param name="taskId">任务ID</param>
        /// <param name="newTitle">新标题</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateTitle(Guid taskId, string newTitle)
        {
            new TaskTitleUpdater().Update(taskId, newTitle);
            return this.Json((object)new { Success = true });
        }
        #endregion

        #region 获取某一领导月日程
        public ActionResult Index(int year, int month, string EmplID)
        {
            try
            {
                var leaderEmployee = orgMgr.GetEmployee(EmplID);
                if (leaderEmployee == null)
                {
                    return new JsonNetResult(new
                    {
                        Success = false,
                        Message = "领导ID无效"
                    });
                }
                else
                {
                    int days = 0;
                    DateTime calendarDateRange = CalendarBiz.GetCalendarDateRange(year, month, out days);
                    DateTime datetime = calendarDateRange;
                    List<DateStatus> dateStatusByMonth = CalendarBiz.GetDateStatusByMonth(EmplID, calendarDateRange, days);
                    //List<CalendarItem> calendarItemList = new List<CalendarItem>();
                    Dictionary<string, object> markDict = new Dictionary<string, object>();
                    for (int index = 0; index < days; ++index)
                    {
                        // 判断状态是否为未完成，为空的不返回
                        if (dateStatusByMonth[index].Status != "empty") {
                            //CalendarItem calendarItem = new CalendarItem()
                            //{
                            //    Year = datetime.Year,
                            //    Month = datetime.Month,
                            //    Day = datetime.Day,
                            //    IsInMonth = datetime.Month == month,
                            //    Status = dateStatusByMonth[index].Status,
                            //};
                            markDict.Add(datetime.ToString("yyyy-%M-%d"), string.Empty);
                        }
                        datetime = datetime.AddDays(1.0);
                    }
                    return this.Json((object)new
                    {
                        Success = true,
                        Data = new
                        {
                            mark = markDict
                        }
                    }, JsonRequestBehavior.AllowGet);
                }
            }
            catch(Exception e)
            {
                LogService.WriteLog("Tiger", "Message:" + e.Message, "Tiger_Debug", LogService.LogLevel.Debug);
                return new JsonNetResult(new
                {
                    Success = false,
                    Message = e.Message
                });
            }
            
        }
        #endregion

        #region 获取某一领导某日任务
        public ActionResult GetByDate(int year, int month, int day, string emplId)
        {
            List<CLD_Task> taskListByDate = TaskBiz.GetTaskListByDate(new DateTime(year, month, day), emplId);
            List<TaskViewModel> taskViewModelList = new List<TaskViewModel>();
            using (CalendarEntities dbInstance = DBHelper.GetDbInstance())
            {
                foreach (CLD_Task taskObj in taskListByDate)
                {
                    TaskViewModel taskViewByTask = TaskBiz.GetTaskViewByTask(taskObj, dbInstance);
                    taskViewModelList.Add(taskViewByTask);
                }
            }
            return (ActionResult)this.Json((object)new
            {
                Success = true,
                Data = new { tasks = taskViewModelList }
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 设置开始时间
        /// <summary>
        /// 设置开始时间（先执行，再执行【设置提醒时间】）
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="hour"></param>
        /// <param name="minute"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateStartTime(Guid taskId, int? hour, int? minute)
        {
            TimeSpan? newValue = new TimeSpan?();
            if (hour.HasValue && minute.HasValue)
                newValue = new TimeSpan?(new TimeSpan(hour.Value, minute.Value, 0));
            new TaskStartTimeUpdater().Update(taskId, newValue);
            return this.Json((object)new { Success = true });
        }
        #endregion

        #region 更新提醒时间
        /// <summary>
        /// 更新提醒时间
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="dayOffset"></param>
        /// <param name="hourOffset"></param>
        /// <param name="minuteOffset"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateRemind(Guid taskId, int? dayOffset, int? hourOffset, int? minuteOffset)
        {
            using (CalendarEntities dbInstance = DBHelper.GetDbInstance())
            {
                if (dayOffset.HasValue && hourOffset.HasValue && minuteOffset.HasValue)
                {
                    int totalMinutes = (int)new TimeSpan(dayOffset.Value, hourOffset.Value, minuteOffset.Value, 0).TotalMinutes;
                    RemindBiz.UpdateRemind(taskId, totalMinutes, dbInstance);
                }
                else if (dbInstance.CLD_Remind.Any<CLD_Remind>((Expression<Func<CLD_Remind, bool>>)(s => s.TaskID == (Guid?)taskId)))
                    RemindBiz.DeleteRemind(taskId, dbInstance);
                return this.Json((object)new { Success = true });
            }
        }
        #endregion

        #region 获取提醒时间与开始时间偏移量
        [HttpPost]
        public JsonResult GetRemindOffset(Guid taskId)
        {
            using (CalendarEntities dbInstance = DBHelper.GetDbInstance())
            {
                CLD_Remind cldRemind = dbInstance.CLD_Remind.SingleOrDefault<CLD_Remind>((Expression<Func<CLD_Remind, bool>>)(s => s.TaskID == (Guid?)taskId));
                if (cldRemind == null)
                    return this.Json((object)new
                    {
                        Success = true,
                        IsRemind = false
                    });
                return this.Json((object)new
                {
                    Success = true,
                    IsRemind = true,
                    TotalMinutesOffset = cldRemind.RemindTimeOffsetMinutes
                });
            }
        }
        #endregion

        #region 读取秘书-领导配置关系
        public ActionResult GetLeaders()
        {   try
            {
                /*
                 * 解析秘书-领导关系
                 */
                var employee = (User.Identity as AppkizIdentity).Employee;

                using (StreamReader sr = new StreamReader(Server.MapPath("~/relation.json")))
                {
                    var relation = JsonConvert.DeserializeObject<Relation>(sr.ReadToEnd());
                    List<LeaderRelation> leaderRelations = relation.relation;
                    var leaderRelation = leaderRelations.Where(n => n.secretary.id == employee.EmplID).FirstOrDefault();
                    if(leaderRelation == null)
                    {
                        return new JsonNetResult(new
                        {
                            Success = false,
                            Message = "当前用户无对应领导关系"
                        });
                    }
                    else
                    {
                        return new JsonNetResult(new
                        {
                            Success = true,
                            Data = new
                            {
                                relations = leaderRelation.leaders
                            }
                        });
                    }
                }
            }
            catch(Exception e)
            {
                LogService.WriteLog("Tiger", "Message:" + e.Message, "Tiger_Debug", LogService.LogLevel.Debug);
                return new JsonNetResult(new
                {
                    Success = false,
                    Message = e.Message
                });
            }

        }
        #endregion

        #region 获取当前用户日程权限
        public ActionResult GetCalendarPerm()
        {
            try
            {
                /*
                 * 变量定义
                 */
                // 权限字符串
                var perm = string.Empty;

                /*
                 * 获取当前用户权限
                 */
                var employee = (User.Identity as AppkizIdentity).Employee;

                // 检测领导日程查看权限
                bool canSeeLeader = AppPermission.CheckPermission(employee.EmplID, "canSeeLeader");
                // 检测领导日程设置权限
                bool canScheduleLeader = AppPermission.CheckPermission(employee.EmplID, "canScheduleLeader");
                // 检测是否是管理员
                bool isAdmin = AppPermission.CheckPermission(employee.EmplID, "admin");

                if (isAdmin)
                {
                    perm = "11";
                }
                else
                {
                    perm = string.Format("{0}{1}", canSeeLeader ? 1 : 0, canScheduleLeader ? 1 : 0);
                }

                return new JsonNetResult(new
                {
                    Success = true,
                    Data = new
                    {
                        perm = perm
                    }
                });
            }
            catch (Exception e)
            {
                LogService.WriteLog("Tiger", "Message:" + e.Message, "Tiger_Debug", LogService.LogLevel.Debug);
                return new JsonNetResult(new
                {
                    Success = false,
                    Message = e.Message
                });
            }
        }
        #endregion
    }
}